<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>回到顶部</title>
    <style>
        body {
            height: 2000px;
        }

        button {
            position: fixed;
            right: 50px;
            bottom: 50px;
        }
    </style>
</head>

<body>
    <button id="goTop">回到顶部</button>

    <script>
        //方法一
        // goTop.onclick = function () {
        //     document.documentElement.scrollTop = 0
        // }
        //方法二
        goTop.onclick = function () {
            var timer = setInterval(function () {
                var top = document.documentElement.scrollTop || document.body.scrollTop
                document.documentElement.scrollTop -= 20
                console.log("正在回到顶部...");
                //如果回到顶部了，则关闭定时器
                if (top <= 0) {
                    clearInterval(timer)
                }
            }, 30)
        }
    </script>
</body>

</html>